package com.icms.core.service;

import java.util.HashMap;
import java.util.Map;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import com.icms.common.basic.BaseService;
import com.icms.common.config.AppConst;
import com.icms.core.model.Admin;
import com.jfinal.aop.Enhancer;
import com.jfinal.plugin.ehcache.CacheKit;

public class AdminService extends BaseService {

	public static final AdminService service = Enhancer.enhance(AdminService.class);
	private final  String table = " ic_admin ";
	private final  String cacheName = AppConst.SERVICE_CACHE[AppConst.ADMIN_CACHE];

	public Admin getAdminByUsername(String username) {
		String sql = "select * from " + table + "  where username = ?";
		return Admin.dao.findFirstByCache(cacheName, "string" + username, sql, username);
	}

	public Map<String, Object> login(String username, String password, boolean remberme) {
		Subject currentUser = SecurityUtils.getSubject();
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("success", false);
		UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
		if (remberme) {
			usernamePasswordToken.setRememberMe(true);
		}
		try {
			currentUser.login(usernamePasswordToken);
			currentUser.getSession().setAttribute(AppConst.SESSION_ADMIN, username);
			result.put("success", true);
			result.put("msg", "登录成功！");
		} catch (AuthenticationException e) {
			e.printStackTrace();
			result.put("msg", "账号或密码输入错误！");
		}
		return result;

	}


	@Override
	protected void clearCacheAll() {
		 CacheKit.removeAll(cacheName);
	}
}
